const http = require('http');
const url = require('url');
const fs = require('fs');
const Hand = require('./js/pokersolver.js').Hand;

// 房间
var rooms = [];
var server = http.createServer((req, res) => {
    rooms.push({
        ante: 30,
        nowAnte: 20,
        pot: 0,
        communityCardPoker: [],
        communityCardPokerLastround : [],
        communityCardPokerIns: [],
        roomNumber: '000000',
        roundnumber: 0,
        isStart: false,
        playersMsg: [
            MysqlPlayersMsg.find(array => array.name === '空位0'),
            MysqlPlayersMsg.find(array => array.name === '空位1'),
            MysqlPlayersMsg.find(array => array.name === '空位2'),
            MysqlPlayersMsg.find(array => array.name === '空位3'),
            MysqlPlayersMsg.find(array => array.name === '空位4'),
            MysqlPlayersMsg.find(array => array.name === '空位5'),
            MysqlPlayersMsg.find(array => array.name === '空位6'),
            MysqlPlayersMsg.find(array => array.name === '空位7'),
            MysqlPlayersMsg.find(array => array.name === '空位8'),
        ],
        roundData: {
            bets: [],
            preFlop: [],
            Flop: [],
            Turn: [],
        },
        smallBlind: 10,
        bigBlind: 20,
        isBBwent: false,
        deck: [],
        currTurn: 0,//0 翻前 1 翻牌 2 转牌 3 河底
        finish: false,
        sbId: 0,
        bbId: 0,
        wlData: [],
        dealerPosition:0,
        winInvest : 0,
        winOuts:[],
        winOdds:0,
        reveal : false,
        winInfo :[],
        lastFlop:[],
    })
    // 跨域
    // res.setHeader('Access-Control-Allow-Origin', '*');
    // url信息
    let { method, headers: requestHeaders } = req,
        { pathname, query } = url.parse(req.url, true),
        pathREG = /\.([a-z0-9]+)$/i;
    if (req.url === '/') {
        res.writeHead(302, { 'Location': '/login.html' });
        res.end();
    }
    // 测试
    // else if (pathname === '/testRoom') {
    //     MysqlPlayersMsg.find(array => array.name === '涛哥').isDealer = true;
    //     rooms.push({
    //         ante: 100,
    //         nowAnte: 100,
    //         pot: 0,
    //         theFlop: [],
    //         communityCardPoker: [],
    //         roundnumber: 0,
    //         roomNumber: query.roomNumber,
    //         trunNumber: 1,
    //         isStart: false,
    //         playersMsg: [
    //             MysqlPlayersMsg.find(array => array.name === '涛哥'),
    //             MysqlPlayersMsg.find(array => array.name === '刘诗诗'),
    //             MysqlPlayersMsg.find(array => array.name === '打款机'),

    //             //  MysqlPlayersMsg.find(array => array.name === '狼人'),
    //             // MysqlPlayersMsg.find(array => array.name === '阿斯顿'),
    //         ]
    //     })
    //     res.end(JSON.stringify(
    //         {
    //             name: query.name,
    //             roomNumber: query.roomNumber,
    //         }
    //     ))
    // }
    // 创建游戏
    // else if (pathname === '/creatRoom') {
    //     if (query.roomNumber.length !== 6) {
    //         res.end(JSON.stringify(
    //             {
    //                 code: 306,
    //                 prompt: '房间号为6位数'
    //             }
    //         ))
    //     }
    //     else if (false) {
    //         // 改房间已存在
    //     }
    //     else if (!MysqlPlayersMsg.find(array => array.name === query.name)) {
    //         res.end(JSON.stringify(
    //             {
    //                 code: 304,
    //                 prompt: '用户不存在'
    //             }
    //         ))
    //     }
    //     else if (false) {
    //         console.log('一个账号只能房间游戏')
    //     }
    //     else {
    //         rooms.push({
    //             ante: 30,
    //             nowAnte: 20,
    //             pot: 0,
    //             communityCardPoker: [],
    //             communityCardPokerIns: [],
    //             roomNumber: query.roomNumber,
    //             roundnumber: 0,
    //             isStart: false,
    //             playersMsg: [
    //                 MysqlPlayersMsg.find(array => array.name === query.name),
    //                 MysqlPlayersMsg.find(array => array.name === '空位1'),
    //                 MysqlPlayersMsg.find(array => array.name === '空位2'),
    //                 MysqlPlayersMsg.find(array => array.name === '空位3'),
    //                 MysqlPlayersMsg.find(array => array.name === '空位4'),
    //                 MysqlPlayersMsg.find(array => array.name === '空位5'),
    //                 MysqlPlayersMsg.find(array => array.name === '空位6'),
    //                 MysqlPlayersMsg.find(array => array.name === '空位7'),
    //                 MysqlPlayersMsg.find(array => array.name === '空位8'),
    //             ],
    //             roundData: {
    //                 bets: [],
    //                 preFlop: [],
    //                 Flop: [],
    //                 Turn: [],
    //             },
    //             smallBlind: 10,
    //             bigBlind: 20,
    //             isBBwent: false,
    //             deck: [],
    //             currTurn: 0,//0 翻前 1 翻牌 2 转牌 3 河底
    //             finish: false,
    //             sbId: 0,
    //             bbId: 0,
    //             wlData: [],
    //             dealerPosition:0,
    //             winInvest : 0,
    //             winOuts:[],
    //             winOdds:0,
    //             reveal : false,
    //             winInfo :[],
    //             lastFlop:[],
    //         })
    //         res.end(JSON.stringify(
    //             {
    //                 code: 200,
    //                 name: query.name,
    //                 roomNumber: query.roomNumber,
    //             }
    //         ))
    //     }
    // }
    // 进入游戏
    else if (pathname === '/joinRoom') {
        var room = rooms.find((array => array.roomNumber === query.roomNumber))
        if (room == undefined){
            res.end(JSON.stringify(
                {
                    code: 306,
                    prompt: '房间不存在'
                }
            ))
        }
        // else if (query.roomNumber.length !== 6) {
        //     res.end(JSON.stringify(
        //         {
        //             code: 306,
        //             prompt: '房间号为6位数'
        //         }
        //     ))
        // }
        // 用户不存在
        else if (!MysqlPlayersMsg.find(array => array.name === query.name)) {
            res.end(JSON.stringify(
                {
                    code: 304,
                    prompt: '用户不存在'
                }
            ))
        }
        else if(!MysqlPlayersMsg.find(array => array.id === query.pwd && array.name === query.name)){
            res.end(JSON.stringify(
                {
                    code: 304,
                    prompt: '密码错误'
                }
            ))
        }
         // 用户已在该房间
        else if (room.playersMsg.findIndex((array => array.name === query.name)) != -1) {
            res.end(JSON.stringify(
                {
                    code: 200,
                    name: query.name,
                    roomNumber: query.roomNumber,
                }
            ))
        }
        // 用户是管理员
        else if (query.name === '管理员') {
            res.end(JSON.stringify(
                {
                    code: 200,
                    name: room.playersMsg[0].name,
                    roomNumber: query.roomNumber,
                }
            ))
        }
        //对局人满开启观战
        // else if (room.playersMsg.length === 9) {
        //     // res.end(JSON.stringify(
        //     //     {
        //     //         code: 307,
        //     //         prompt: '对局已经开始'
        //     //     }
        //     // ))
        //     res.end(JSON.stringify(
        //         {
        //             code: 200,
        //             name: query.name,
        //             roomNumber: query.roomNumber,
        //         }
        //     ))
        // }
        else {
            console.log(query.name + '加入游戏')
            if (room.playersMsg[0].robot ===true){//第一个加入的坐0位
                room.playersMsg[0]=(MysqlPlayersMsg.find(array => array.name === query.name))
                room.playersMsg[0].isDealer = true;
            }else {
                let randomNumber = Math.floor(Math.random() * 8) + 1;
                if (room.playersMsg[randomNumber].robot == false) {
                    let count = 1
                    do {
                        randomNumber = randomNumber + 1 >= room.playersMsg.length ? 0 : randomNumber + 1;
                        count++;
                    } while (
                        //被占位的跳过（robot = false)
                    room.playersMsg[randomNumber].robot == false
                    && count < Object.keys(room.playersMsg).length * 2 // Avoid infinite loop, allow search twice on all players
                        );
                }
                room.playersMsg[randomNumber] = (MysqlPlayersMsg.find(array => array.name === query.name))
            }
            res.end(JSON.stringify(
                {
                    code: 200,
                    name: query.name,
                    roomNumber: query.roomNumber,
                }
            ))
             // 广播给当前分组所有人
             io.to(query.roomNumber).emit('rendering__game__to__client',
             JSON.stringify(rooms.find((array => array.roomNumber === query.roomNumber)))
         );
        }
    }
    else if (pathname === '/viewRoom'){
        var room = rooms.find((array => array.roomNumber === query.roomNumber))
        res.end(JSON.stringify(
            {
                code: 200,
                room: room,
            }
        ))
    }
    // 获取房间数据
    else if (pathname === '/getRoomMsg') {
        res.end(JSON.stringify(
            {
                code: 200,
                roomMsg: rooms.find((array => array.roomNumber === query.roomNumber))
            }
        ))
    }
    // 静态资源
    else if (pathname === '/login.html') {
        res.end(fs.readFileSync('./login.html', 'utf-8'));
    }
    if (pathname === '/holdem.html') {
        res.end(fs.readFileSync('./holdem.html', 'utf-8'));
    }
    else if (
        pathname.substring(0, 8) === '/images/' ||
        pathname.substring(0, 4) === '/js/' ||
        pathname.substring(0, 5) === '/css/' ||
        pathname.substring(0, 7) === '/sound/'
    ) {
        fs.readFile('.' + req.url, (err, data) => {
            if (err) { console.log(err) } else { res.end(data) }
        })
    }
}).listen(3000, () => {
});

var io = require('socket.io')(server);

// 监听连接事件
io.on('connection', function (socket) {
    var groupid = url.parse(socket.request.url, true).query.groupid; // 获取分组号
    socket.join(groupid);  // 加入分组

    // chat
    socket.on('clear',function(data){
        var index = rooms.findIndex((array => array.roomNumber === data.roomNumber))
        io.to(groupid).emit('getout', {});
        for (let i =0 ; i <rooms[index].playersMsg.length ; i ++){
            if (rooms[index].playersMsg[i].robot === false){
                rooms[index].playersMsg[i].statusChipsLeftover = 2000
                rooms[index].playersMsg[i].theFlop = []
                rooms[index].playersMsg[i].buyIns = 0
                rooms[index].playersMsg[i].blindValue = ''
                rooms[index].playersMsg[i].isDealer = false
                rooms[index].playersMsg[i].allIn = false
                rooms[index].playersMsg[i].isTrun = false
                rooms[index].playersMsg[i].isFold = true
                rooms[index].playersMsg[i].bringIn =2000
                rooms[index].playersMsg[i].exit = false
                rooms[index].playersMsg[i].style = ''
                rooms[index].playersMsg[i].number = ''
                rooms[index].playersMsg[i].showFlop = []
                rooms[index].playersMsg[i].isWinner = false
                rooms[index].playersMsg[i].buying = false
                rooms[index].playersMsg[i].secondBuying = false
                rooms[index].playersMsg[i].isDown = false
            }
        }
       rooms[index] ={
           ante: 30,
           nowAnte: 20,
           pot: 0,
           communityCardPoker: [],
           communityCardPokerLastround : [],
           communityCardPokerIns: [],
           roomNumber: '000000',
           roundnumber: 0,
           isStart: false,
           playersMsg: [
               MysqlPlayersMsg.find(array => array.name === '空位0'),
               MysqlPlayersMsg.find(array => array.name === '空位1'),
               MysqlPlayersMsg.find(array => array.name === '空位2'),
               MysqlPlayersMsg.find(array => array.name === '空位3'),
               MysqlPlayersMsg.find(array => array.name === '空位4'),
               MysqlPlayersMsg.find(array => array.name === '空位5'),
               MysqlPlayersMsg.find(array => array.name === '空位6'),
               MysqlPlayersMsg.find(array => array.name === '空位7'),
               MysqlPlayersMsg.find(array => array.name === '空位8'),
           ],
           roundData: {
               bets: [],
               preFlop: [],
               Flop: [],
               Turn: [],
           },
           smallBlind: 10,
           bigBlind: 20,
           isBBwent: false,
           deck: [],
           currTurn: 0,//0 翻前 1 翻牌 2 转牌 3 河底
           finish: false,
           sbId: 0,
           bbId: 0,
           wlData: [],
           dealerPosition:0,
           winInvest : 0,
           winOuts:[],
           winOdds:0,
           reveal : false,
           winInfo :[],
           lastFlop:[],
       }
    });
    socket.on('chat__to__server', function (data) {
        rdata = {
            id: data.id,
            content: data.content,
            avatar: data.avatar,
            name: data.name,
            socketid: socket.id,
        }
console.log(data)
        io.to(groupid).emit('chat__to__client', JSON.stringify(rdata));
    });



    socket.on('start__game__to__server', function (data) {


        socket.join(socket.roomNumber);


        var room = rooms.find((array => array.roomNumber === data.roomNumber));
        // console.log(room.playersMsg)
        // 已经开始游戏
        if (room.isStart) return

        // 玩家太少，无法开始游戏
        let liveplayers = 0
        for (let i =0 ; i <room.playersMsg.length ; i ++){
            if (room.playersMsg[i].exit == false && room.playersMsg[i].robot == false) liveplayers++
        }
        if (liveplayers<2) {
            setTimeout(() => socket.emit('start__game__to__client',
                {}), 5000)
            return
        }
        room.roundnumber++
        console.log('手数' + room.roundnumber)
        //保存上局手牌数据
        room.lastFlop=[];

        if (room.roundnumber>1) {
            let totalBet =  totalInvest(room.playersMsg, room.roundData.bets, room.roundData.preFlop, room.roundData.Flop, room.roundData.Turn)
            for (let i = 0; i < room.playersMsg.length; i++) {
                if (room.playersMsg[i].robot == false) {
                    let bet = totalBet.filter((item)=>item.player === room.playersMsg[i].name).length !=0 ?totalBet.filter((item)=>item.player === room.playersMsg[i].name)[0].bet : '';
                    let pot = room.winInfo.filter((item)=>item.name === room.playersMsg[i].name).length !=0 ?room.winInfo.filter((item)=>item.name === room.playersMsg[i].name)[0].pot : '';
                    let hand =  room.winInfo.filter((item)=>item.name === room.playersMsg[i].name).length!= 0 ? room.winInfo.filter((item)=>item.name === room.playersMsg[i].name)[0].hand : '';
                    room.lastFlop.push({
                        name: room.playersMsg[i].name,
                        showFlop: room.playersMsg[i].showFlop,
                        theFlop: room.playersMsg[i].theFlop,
                        totalBet:bet,
                        winPot:pot,
                        hand:hand,
                    })
                }
            }
        }

        //初始化下注对局参数
        room.communityCardPokerLastround = room.communityCardPoker
        room.ante = 30;
        room.nowAnte = 20;
        room.pot = 0;
        room.currTurn = 0;
        room.isBBwent = false;
        room.finish = false;
        room.roundData.bets = [];
        room.roundData.preFlop = [];
        room.roundData.Flop = [];
        room.deck = dealPoker();
        room.communityCardPoker= [];
        room.communityCardPokerIns=[];
        room.winInvest = 0;
        room.winOuts=[];
        room.winOdds=0;
        room.reveal = false;
        room.winInfo = [];


        //最后一局允许离开
        if (room.roundnumber == 100) {
            for (let i = 0; i < room.playersMsg.length; i++) {
                room.playersMsg[i].isDown = true
            }
        }
        if (room.roundnumber > 100) return
            //初始化玩家数据
        for (let i = 0; i < room.playersMsg.length; i++) {
            room.playersMsg[i].style = '';
            room.playersMsg[i].number= 0;
            if (room.playersMsg[i].exit==false) {
                room.playersMsg[i].isFold = false// 离开玩家焊死
            }
            room.playersMsg[i].allIn = false
            room.playersMsg[i].isDealer = false
            room.playersMsg[i].isTrun = false
            room.playersMsg[i].showFlop = []
            room.playersMsg[i].isWinner = false ;
            room.playersMsg[i].autoFold = false;
            room.playersMsg[i].autoCheck = false;
            room.playersMsg[i].blindValue = '';
        }


        //跳过机器人
        //庄家
        let count =1
        do {
            room.dealerPosition = room.dealerPosition + 1 >= room.playersMsg.length ? 0 :  room.dealerPosition + 1;
            count++;
        } while (
            //占位的跳过（robot = true)
        room.playersMsg[room.dealerPosition].robot== true
        && count < Object.keys(room.playersMsg).length * 2 // Avoid infinite loop, allow search twice on all players
            );
        room.playersMsg[room.dealerPosition].isDealer = true
        //小盲
        count =1
        var sbPosition = room.dealerPosition
        do {
            sbPosition = sbPosition + 1 >= room.playersMsg.length ? 0 :  sbPosition + 1;
            count++;
        } while (
            //占位的跳过（robot = true)
        room.playersMsg[sbPosition].robot== true
        && count < Object.keys(room.playersMsg).length * 2 // Avoid infinite loop, allow search twice on all players
            );
        //大盲
        count =1
        var bbPosition = sbPosition
        do {
            bbPosition = bbPosition + 1 >= room.playersMsg.length ? 0 :  bbPosition + 1;
            count++;
        } while (
            //占位的跳过（robot = true)
        room.playersMsg[bbPosition].robot== true
        && count < Object.keys(room.playersMsg).length * 2 // Avoid infinite loop, allow search twice on all players
            );
        //第一个行动玩家
        var firstToGo = bbPosition
        count = 1
        do {
            firstToGo = firstToGo + 1 >= room.playersMsg.length ? 0 :  firstToGo + 1;
            count++;
        } while (
            //占位的跳过（robot = true) 离开的跳过
            (room.playersMsg[firstToGo].robot== true||room.playersMsg[firstToGo].exit== true)
        && count < Object.keys(room.playersMsg).length * 2 // Avoid infinite loop, allow search twice on all players
            );

        room.playersMsg[sbPosition].blindValue = 'Small Blind'
        room.playersMsg[bbPosition].blindValue = 'Big Blind'
        //底池投入大小盲注
        room.roundData.bets.push({
            player: room.playersMsg[sbPosition].id,
            bet: room.smallBlind,
        });
        room.roundData.bets.push({
            player: room.playersMsg[bbPosition].id,
            bet: room.bigBlind,
        });
        //写入bbid 用于后续检查大盲行动了没
        room.bbId = bbPosition
        //写入sbId,用于更新每轮firsttogo
        room.sbId = sbPosition

        // 大小盲状态
        room.playersMsg[sbPosition].style = 'status__info--bet';
        room.playersMsg[sbPosition].number = room.smallBlind;
        room.playersMsg[bbPosition].style = 'status__info--bet';
        room.playersMsg[bbPosition].number = room.bigBlind;
        


        //初始化大小盲剩余筹码
        room.playersMsg[sbPosition].statusChipsLeftover = room.playersMsg[sbPosition].statusChipsLeftover - room.smallBlind
        room.playersMsg[bbPosition].statusChipsLeftover = room.playersMsg[bbPosition].statusChipsLeftover - room.bigBlind
        // 设置isTrun
        room.playersMsg[firstToGo].isTrun = true
        //初始化底池和大盲注
        room.nowAnte = 20;
        room.pot = 30;
        //  检查buyin
        for (let i = 0; i < room.playersMsg.length; i++) {
            room.playersMsg[i].bringIn += 1000 * room.playersMsg[i].buyIns
            room.playersMsg[i].statusChipsLeftover += 1000 * room.playersMsg[i].buyIns
            room.playersMsg[i].buyIns = 0
        }
        // 没钱自动买入（此时大盲已经下注，不够支付大盲时此时为负，自动买入）
        for (let i = 0; i < room.playersMsg.length; i++) {
            if (room.playersMsg[i].statusChipsLeftover <= 0 && room.playersMsg[i].robot == false) {
                do {
                    room.playersMsg[i].statusChipsLeftover += 1000
                    room.playersMsg[i].buyIns++
                }
                while (room.playersMsg[i].statusChipsLeftover <= 0)
                room.playersMsg[i].bringIn += 1000 * room.playersMsg[i].buyIns
                room.playersMsg[i].buyIns = 0
            }
        }

        // 发底牌
        for (var i = 0; i < room.playersMsg.length; i++) {
            if(room.playersMsg[i].robot == false) {//机器人不发牌
                room.playersMsg[i].theFlop = [room.deck.pop(), room.deck.pop()]
            }
        }
        //开启弃牌计时
        // timer =setTimeout(() => socket.emit('cooldownfold',
        //     room.playersMsg[firstToGo].id), 10000)
        // timer1 =setTimeout(() => socket.broadcast.emit('cooldownfold',
        //     room.playersMsg[firstToGo].id), 10000)
        io.to(groupid).emit('coolDown', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
        ));



        // 设置游戏为开始状态
        room.isStart = true;
        //统计战绩
        room.wlData = []
        for (let i = 0; i < room.playersMsg.length; i++) {
            if (room.playersMsg[i].robot == false) {
                room.wlData.push(
                    {
                        name: room.playersMsg[i].name,
                        bringin: room.playersMsg[i].bringIn,
                        asset: room.playersMsg[i].statusChipsLeftover,
                        grade: room.playersMsg[i].statusChipsLeftover - room.playersMsg[i].bringIn,
                    });
            }
        }
        console.log(room.wlData)

        // 也可以只返回牌的信息
        io.to(groupid).emit('rendering__game__to__client', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
        ));

    });
    socket.on('AutoMove', function (data) {
        var room = rooms.find((array => array.roomNumber === data.roomNumber));
        var playersMsgIndex = room.playersMsg.findIndex((array => array.id === data.id));
        if (data.style == 'fold'){
            room.playersMsg[playersMsgIndex].autoFold =true
            room.playersMsg[playersMsgIndex].autoCheck =false
        }else if (data.style == 'check'){
            room.playersMsg[playersMsgIndex].autoCheck =true
            room.playersMsg[playersMsgIndex].autoFold =false
        }else if (data.style == 'checkfold'){
            room.playersMsg[playersMsgIndex].autoCheck =true
            room.playersMsg[playersMsgIndex].autoFold =true
        }
        if (data.style == 'clear'){
            room.playersMsg[playersMsgIndex].autoFold =false
            room.playersMsg[playersMsgIndex].autoCheck =false
        }
        io.to(groupid).emit('rendering__game__to__client', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
        ));
    });
    //insurance
    socket.on('Insurance', function (data) {
        var room = rooms.find((array => array.roomNumber === data.roomNumber));
        var playersMsgIndex = room.playersMsg.findIndex((array => array.id === data.id));
        //防止重复提交
        if (room.playersMsg[playersMsgIndex].isFold === true ||
            (room.currTurn ==1 && room.playersMsg[playersMsgIndex].buying ===false) ||
            (room.currTurn ==2 && room.playersMsg[playersMsgIndex].secondBuying===false)) return

        room.playersMsg[playersMsgIndex].buying =false
        room.playersMsg[playersMsgIndex].secondBuying =false

        for (let i = 0; i < room.playersMsg.length; i++) {
            room.playersMsg[i].isWinner = false ;
        }
        room.communityCardPoker.push(room.deck.pop())
        room.currTurn += 1
        var insurancePay = 0
        if (data.buy == '1') {//投保
            if (data.outs.findIndex((item) => item === room.communityCardPoker[room.communityCardPoker.length - 1]) != -1) {//出补
                room.playersMsg[playersMsgIndex].statusChipsLeftover += data.conpensation;
                insurancePay= data.conpensation;
            }else{//没出
                room.playersMsg[playersMsgIndex].bringIn += data.number;
            }
        }
        if (room.currTurn == 2) {//继续计算保险
            let results = revealCards(room.playersMsg, room.roundData.bets, room.roundData.preFlop, room.roundData.Flop, room.roundData.Turn, room.communityCardPoker, room.pot)
            if (results.filter((a) => a.stair == 0).length ===1){
                let outs = [];
                let invest = 0;
                for (let i = 0; i < room.deck.length; i++) {
                    room.communityCardPokerIns = room.communityCardPoker.concat(room.deck[i])
                    let resultsIns = revealCards(room.playersMsg, room.roundData.bets, room.roundData.preFlop, room.roundData.Flop, room.roundData.Turn, room.communityCardPokerIns, room.pot)
                    resultsIns = resultsIns.filter((a) => a.stair == 0);
                    if (resultsIns.findIndex((a) => a.player === results[0].player) == -1) {//新赢家里面不包括老赢家（分池不算outs）
                        outs.push(room.deck[i])
                        for (let i = 0 ; i <resultsIns.length ; i ++){ //对每一张补牌查看有无边池
                            if (resultsIns[i].invest >=results[0].invest ) {
                                invest = results[0].invest
                                break
                            }
                            else if (resultsIns[i].invest > invest ) {
                                invest = resultsIns[i].invest
                            }
                        }
                    }
                }
                let temptCard =[]//弃牌玩家的牌回归牌库
                for (let i =0 ;i <room.playersMsg.length;i++){
                    if (room.playersMsg[i].isFold == true && room.playersMsg[i].robot == false){
                        if (room.playersMsg[i].theFlop.length >0) {
                            temptCard.push(room.playersMsg[i].theFlop[0]);
                            temptCard.push(room.playersMsg[i].theFlop[1]);
                        }
                    }
                }
                for (let i = 0 ; i <temptCard.length;i++){
                    room.communityCardPokerIns = room.communityCardPoker.concat(temptCard[i])
                    let resultsIns = revealCards(room.playersMsg, room.roundData.bets, room.roundData.preFlop, room.roundData.Flop, room.roundData.Turn, room.communityCardPokerIns, room.pot)
                    resultsIns = resultsIns.filter((a) => a.stair == 0);
                    if (resultsIns.findIndex((a) => a.player === results[0].player) == -1) {//新赢家里面不包括老赢家（分池不算outs）
                        outs.push(temptCard[i])
                        for (let i = 0 ; i <resultsIns.length ; i ++){ //对每一张补牌查看有无边池
                            if (resultsIns[i].invest >=results[0].invest ) {
                                invest = results[0].invest
                                break
                            }
                            else if (resultsIns[i].invest > invest ) {
                                invest = resultsIns[i].invest
                            }
                        }
                    }
                }
                dataIns = {
                    winner: results.find((a) => a.stair == 0).player,
                    outs: outs,
                    invest: invest,
                    odds: calodds(outs),
                }
                room.winInvest = invest
                room.winOuts=outs
                room.winOdds=calodds(outs)
                for (let i = 0 ;i <room.playersMsg.length ; i++){
                    if (room.playersMsg[i].name === results.filter((a) => a.stair == 0)[0].player ){
                        room.playersMsg[i].isWinner = true
                        room.playersMsg[i].secondBuying =true
                    }
                }
                io.to(groupid).emit('callInsurance',dataIns);
                //返回信息
                io.to(groupid).emit('rendering__game__to__client', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
                ));
                return
            }else {
                //非独赢
                room.communityCardPoker.push(room.deck.pop())
                room.currTurn = 3
            }
        }
        if (room.currTurn == 3) {
            console.log('牌发完了，比大小(allin)')
            let results = revealCards(room.playersMsg, room.roundData.bets, room.roundData.preFlop, room.roundData.Flop, room.roundData.Turn, room.communityCardPoker, room.pot)
            console.log(results)
            //结算
            for (players of room.playersMsg) {
                if (results.findIndex((p) => p.player === players.name) != -1) {
                    players.statusChipsLeftover += results[results.findIndex((p) => p.player === players.name)].winpot
                    winpotdata = {
                        name: players.name,
                        hand: results[results.findIndex((p) => p.player === players.name)].handTitle,
                        pot: results[results.findIndex((p) => p.player === players.name)].winpot,
                    }
                    console.log(winpotdata)
                    room.winInfo.push({
                        name: players.name,
                        hand: results[results.findIndex((p) => p.player === players.name)].handTitle,
                        pot: results[results.findIndex((p) => p.player === players.name)].winpot,
                    });
                    if (insurancePay !=0 ){
                        room.winInfo.push({
                            name: room.playersMsg[playersMsgIndex].name,
                            hand: '保险',
                            pot: insurancePay,
                        });
                    }
                    io.to(groupid).emit('win',
                        {name: players.name,
                            hand : results[results.findIndex((p) => p.player === players.name)].handTitle,
                            pot: results[results.findIndex((p) => p.player === players.name)].winpot,
                        });
                }
            }

            //返回信息
            io.to(groupid).emit('rendering__game__to__client', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
            ));


            room.finish = true
            room.isStart = false
            console.log('game finish')
            console.log('isstart?'+room.isStart)
            //清空下注显示
            //这里返回 isStart
            io.to(groupid).emit('rendering__game__to__client', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
            ));
            setTimeout(() => socket.emit('start__game__to__client',
                {}), 5000)
        }

    });
    // setState
    socket.on('set__state__to__server', function (data) {
        // console.log(data)
        // console.log('down')
        //先停止倒计时
        // clearTimeout(timer)
        // clearTimeout(timer1)
        // socket.join(socket.roomNumber);
        //首先检查基本信息：下注量，底池改变量，行动值，
        var room = rooms.find((array => array.roomNumber === data.roomNumber));
        var playersMsgIndex = room.playersMsg.findIndex((array => array.id === data.id));
        if (!room.playersMsg[playersMsgIndex].isTrun && data.style !== 'status__info--fold' ||
            room.playersMsg[playersMsgIndex].isFold) {
            return
        }

        // 设置当前玩家筹码
        room.playersMsg[playersMsgIndex].style = data.style;
        // room.playersMsg[playersMsgIndex].number = data.number;放后面更新

        //  行动结束
        room.playersMsg[playersMsgIndex].isTrun = false;

        let checkBet = room.roundData.bets.findIndex(item => item.player == data.id)
        var invest = 0 //本次总共投资

        if (data.style === 'status__info--raise' ||
            data.style === 'status__info--call') {
            //投资量是否超过了后手？
            if (checkBet == -1 && data.number -room.playersMsg[playersMsgIndex].number>=
                room.playersMsg[playersMsgIndex].statusChipsLeftover) {
                invest = data.number//不管什么情况本次投资量都是后手
                if (room.nowAnte < invest) {
                    room.nowAnte = invest
                }
                room.roundData.bets.push(
                    {
                        player: data.id,
                        bet: invest,
                    },
                );
                room.pot = room.pot + invest - room.playersMsg[playersMsgIndex].number;
                room.playersMsg[playersMsgIndex].allIn = true
            } else if (checkBet != -1 && data.number-room.playersMsg[playersMsgIndex].number >=
                room.playersMsg[playersMsgIndex].statusChipsLeftover) {
                invest = data.number//不管什么情况本次投资量都是后手
                if (room.nowAnte < invest) {
                    room.nowAnte = invest
                }
                room.roundData.bets[checkBet].bet = invest;
                room.pot = room.pot + invest - room.playersMsg[playersMsgIndex].number;
                room.playersMsg[playersMsgIndex].allIn = true
            }
            else {//下注量未超过后手
                if (room.nowAnte < data.number) {
                    room.nowAnte = data.number
                }
                //更新下注量，当前玩家是否重复加注
                if (checkBet != -1) {
                    room.pot = room.pot + data.number - room.playersMsg[playersMsgIndex].number;
                    invest = data.number;
                    room.roundData.bets[checkBet].bet = data.number;

                } else {
                    room.roundData.bets.push(
                        {
                            player: data.id,
                            bet: data.number,
                        },
                    );
                    room.pot = room.pot + data.number- room.playersMsg[playersMsgIndex].number;
                    invest = data.number
                }
            }
        }else if (data.style === 'status__info--free'){
            if (room.currTurn !=0) {
                room.roundData.bets.push(
                    {
                        player: data.id,
                        bet: 0,
                    },
                );
                invest = 0
            } else{
                room.roundData.bets[checkBet].bet = room.bigBlind
                invest = room.bigBlind
            }
        }
        else if (data.style === 'status__info--all-in') {
            room.playersMsg[playersMsgIndex].allIn = true
            //allin时下注量为已有下注+本次下注

            if (checkBet != -1) {
                room.roundData.bets[checkBet].bet = data.number
                if (room.nowAnte <  data.number) {
                    room.nowAnte =  data.number
                }
            } else {
                room.roundData.bets.push(
                    {
                        player: data.id,
                        bet: data.number,
                    },
                );
                if (room.nowAnte < data.number) {
                    room.nowAnte = data.number
                }
            }
            room.pot = room.pot + data.number - room.playersMsg[playersMsgIndex].number
            invest = data.number

        } else if (data.style === 'status__info--fold') {
            invest = room.playersMsg[playersMsgIndex].number
            if (checkBet != -1) {
                room.playersMsg[playersMsgIndex].isFold = true;
                room.roundData.bets[checkBet].bet = 'Fold'
            } else {
                // 弃牌
                room.playersMsg[playersMsgIndex].isFold = true;
                room.roundData.bets.push(
                    {
                        player: data.id,
                        bet: 'Fold',
                    },
                );
            }
        }
        //更新剩余筹码
        room.playersMsg[playersMsgIndex].statusChipsLeftover = room.playersMsg[playersMsgIndex].statusChipsLeftover - invest +room.playersMsg[playersMsgIndex].number
        //更新下注量：
        room.playersMsg[playersMsgIndex].number = invest
        //若nowante改变则取消自动过牌
        if ((room.currTurn !=0  &&room.nowAnte!=0 )|| (room.currTurn ==0 && room.nowAnte != room.bigBlind)){
            for(let i=0;i <room.playersMsg.length;i ++){
                room.playersMsg[i].autoCheck = false
            }
        }
        //检查是否全部弃牌
        let numNonFolds = 0;
        let nonFolderPlayer;
        let winnerFold
        for (let i = 0; i < room.playersMsg.length; i++) {
            if (room.playersMsg[i].isFold === false) {
                numNonFolds++;
                nonFolderPlayer = room.playersMsg[i];
                winnerFold = i
            }
        }
        // 未弃牌人数和最近的未弃牌人，如果人数为1则该人为赢家，不为1则不用 [numNonFolds, nonFolderPlayer];
        if (numNonFolds == 1) {
            console.log('allfoldbutone')
            room.playersMsg[winnerFold].statusChipsLeftover = room.playersMsg[winnerFold].statusChipsLeftover + room.pot
            folddata = {
                name: room.playersMsg[winnerFold].name,
                hand: '弃牌',
                pot: room.pot,
            }
            room.finish = true
            room.winInfo.push({
                name: room.playersMsg[winnerFold].name,
                hand: '弃牌',
                pot: room.pot,
            });
            console.log(room.winInfo)
            io.to(groupid).emit('win',
                {name: room.playersMsg[winnerFold].name,
                    hand :'弃牌',
                    pot: room.pot,
                });;
        }
        //下一位玩家行动/全部allin/回合结束

        //检查回合是否结束
        let allPlayersPresent = false;
        let numUnfolded = 0;
        for (let i = 0; i < room.playersMsg.length; i++) {
            if (room.playersMsg[i].isFold == false && room.playersMsg[i].allIn == false) numUnfolded++;
        }
        const currRound = room.roundData.bets;
        allPlayersPresent =
            currRound.filter((a) => a.bet != 'Fold' &&
                room.playersMsg.find((item) => item.id === a.player).allIn == false).length >= numUnfolded
        let allPlayersCall = true;
        for (let i = 0; i < room.roundData.bets.length; i++) {
            if (room.roundData.bets[i].bet != room.nowAnte) {
                if (room.playersMsg[room.playersMsg.findIndex((item) => item.id == room.roundData.bets[i].player)].isFold != true &&
                    room.playersMsg[room.playersMsg.findIndex((item) => item.id == room.roundData.bets[i].player)].allIn != true) {
                    allPlayersCall = false;
                    break;
                }
            }
        }


        //检查大盲行动了没 开局前改false 翻前变true 一直ture
        if (data.id == room.playersMsg[room.bbId].id) {
            room.isBBwent = true
        }

        //先检查allin
        let participatingPlayers = 0;
        let participatingPlayer = [];
        let allinPlayers = 0;
        for (player of room.playersMsg) {
            if (player.allIn == false && player.isFold == false) {
                participatingPlayers++
                participatingPlayer = [player]
            };
            if (player.allIn == true) allinPlayers++;
        }

        if ((numNonFolds > 1 && participatingPlayers < 1) ||//未弃牌大于1 并且未allin也未弃牌玩家=0 （未弃牌的都allin了）
            (allinPlayers > 0 && participatingPlayers == 1 && //allin大于0 并且未allin也未弃牌玩家只有一个 并且 该玩家有过下注 并且该玩家下注大于等于allin值
                room.roundData.bets.find((item) => item.player === participatingPlayer[0].id) != undefined &&
                room.roundData.bets.find((item) => item.player === participatingPlayer[0].id).bet >= room.nowAnte
            ))
        //排除全都fold情况和一家allin其他全fold情况，该情况直接结算 nonfolds==1
        {

            console.log('allplayersallin')
            room.reveal = true
            for (let i=0;i <room.playersMsg.length ; i ++){
                if (room.playersMsg[i].isFold != true){
                    room.playersMsg[i].showFlop = room.playersMsg[i].theFlop
                    console.log(room.playersMsg[i].showFlop)
                }
            }
            if (room.currTurn == 0) {//翻前不发保险
                room.communityCardPoker = [room.deck.pop(), room.deck.pop(), room.deck.pop()]
                room.currTurn += 1
            }
            if (room.currTurn != 0) {
                if (room.currTurn == 1) {
                    let results = revealCards(room.playersMsg, room.roundData.bets, room.roundData.preFlop, room.roundData.Flop, room.roundData.Turn, room.communityCardPoker, room.pot)

                    if (results.filter((a) => a.stair == 0).length ===1){
                    let outs = [];
                    let invest = 0;
                    for (let i = 0; i < room.deck.length; i++) {
                        room.communityCardPokerIns = room.communityCardPoker.concat(room.deck[i])
                        let resultsIns = revealCards(room.playersMsg, room.roundData.bets, room.roundData.preFlop, room.roundData.Flop, room.roundData.Turn, room.communityCardPokerIns, room.pot)
                        resultsIns = resultsIns.filter((a) => a.stair == 0);
                            if (resultsIns.findIndex((a) => a.player === results[0].player) == -1) {//新赢家里面不包括老赢家（分池不算outs）
                                outs.push(room.deck[i])
                                for (let i = 0 ; i <resultsIns.length ; i ++){ //对每一张补牌查看有无边池
                                    if (resultsIns[i].invest >=results[0].invest ) {
                                        invest = results[0].invest
                                        break
                                    }
                                    else if (resultsIns[i].invest > invest ) {
                                        invest = resultsIns[i].invest
                                    }
                                }
                        }
                    }
                    let temptCard =[]//弃牌玩家的牌回归牌库
                        for (let i =0 ;i <room.playersMsg.length;i++){
                            if (room.playersMsg[i].isFold == true && room.playersMsg[i].robot == false){
                                if (room.playersMsg[i].theFlop.length >0) {
                                    temptCard.push(room.playersMsg[i].theFlop[0]);
                                    temptCard.push(room.playersMsg[i].theFlop[1]);
                                }
                            }
                        }
                        for (let i = 0 ; i <temptCard.length;i++){
                            room.communityCardPokerIns = room.communityCardPoker.concat(temptCard[i])
                            let resultsIns = revealCards(room.playersMsg, room.roundData.bets, room.roundData.preFlop, room.roundData.Flop, room.roundData.Turn, room.communityCardPokerIns, room.pot)
                            resultsIns = resultsIns.filter((a) => a.stair == 0);
                            if (resultsIns.findIndex((a) => a.player === results[0].player) == -1) {//新赢家里面不包括老赢家（分池不算outs）
                                outs.push(temptCard[i])
                                for (let i = 0 ; i <resultsIns.length ; i ++){ //对每一张补牌查看有无边池
                                    if (resultsIns[i].invest >=results[0].invest ) {
                                        invest = results[0].invest
                                        break
                                    }
                                    else if (resultsIns[i].invest > invest ) {
                                        invest = resultsIns[i].invest
                                    }
                                }
                            }
                        }
                    dataIns = {
                        winner: results.find((a) => a.stair == 0).player,
                        outs: outs,
                        invest: invest,
                        odds: calodds(outs),
                    }
                    room.winInvest = invest
                        room.winOuts=outs
                        room.winOdds=calodds(outs)
                    for (let i = 0 ;i <room.playersMsg.length ; i++){
                        if (room.playersMsg[i].name === results.filter((a) => a.stair == 0)[0].player ){
                            room.playersMsg[i].isWinner = true
                            room.playersMsg[i].buying = true //防止重复提交
                        }
                    }
                    //停止计时条
                        io.to(groupid).emit('coolDown', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
                        ));
                        io.to(groupid).emit('callInsurance',dataIns);
                        //返回信息
                        io.to(groupid).emit('rendering__game__to__client', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
                        ));
                    return
                    }else {
                        //非独赢
                        room.communityCardPoker.push(room.deck.pop())
                        room.currTurn = 2

                    }
                }
                if (room.currTurn == 2) {
                    let results = revealCards(room.playersMsg, room.roundData.bets, room.roundData.preFlop, room.roundData.Flop, room.roundData.Turn, room.communityCardPoker, room.pot)
                    if (results.filter((a) => a.stair == 0).length ===1){
                        let outs = [];
                        let invest = 0 ;
                        for (let i = 0; i < room.deck.length; i++) {
                            room.communityCardPokerIns = room.communityCardPoker.concat(room.deck[i])
                            let resultsIns = revealCards(room.playersMsg, room.roundData.bets, room.roundData.preFlop, room.roundData.Flop, room.roundData.Turn, room.communityCardPokerIns, room.pot)
                            resultsIns = resultsIns.filter((a) => a.stair == 0);
                            if (resultsIns.findIndex((a) => a.player === results[0].player) == -1) {//新赢家里面不包括老赢家（分池不算outs）
                                outs.push(room.deck[i])
                                for (let i = 0 ; i <resultsIns.length ; i ++){ //对每一张补牌查看有无边池
                                    if (resultsIns[i].invest >=results[0].invest ) {
                                        invest = results[0].invest
                                        break
                                    }
                                    else if (resultsIns[i].invest > invest ) {
                                        invest = resultsIns[i].invest
                                    }
                                }
                            }
                        }
                        let temptCard =[]//弃牌玩家的牌回归牌库
                        for (let i =0 ;i <room.playersMsg.length;i++){
                            if (room.playersMsg[i].isFold == true && room.playersMsg[i].robot == false){
                                if (room.playersMsg[i].theFlop.length >0) {
                                    temptCard.push(room.playersMsg[i].theFlop[0]);
                                    temptCard.push(room.playersMsg[i].theFlop[1]);
                                }
                            }
                        }
                        for (let i = 0 ; i <temptCard.length;i++){
                            room.communityCardPokerIns = room.communityCardPoker.concat(temptCard[i])
                            let resultsIns = revealCards(room.playersMsg, room.roundData.bets, room.roundData.preFlop, room.roundData.Flop, room.roundData.Turn, room.communityCardPokerIns, room.pot)
                            resultsIns = resultsIns.filter((a) => a.stair == 0);
                            if (resultsIns.findIndex((a) => a.player === results[0].player) == -1) {//新赢家里面不包括老赢家（分池不算outs）
                                outs.push(temptCard[i])
                                for (let i = 0 ; i <resultsIns.length ; i ++){ //对每一张补牌查看有无边池
                                    if (resultsIns[i].invest >=results[0].invest ) {
                                        invest = results[0].invest
                                        break
                                    }
                                    else if (resultsIns[i].invest > invest ) {
                                        invest = resultsIns[i].invest
                                    }
                                }
                            }
                        }
                        dataIns = {
                            winner: results.find((a) => a.stair == 0).player,
                            outs: outs,
                            invest: invest,
                            odds: calodds(outs),
                        }
                        room.winInvest = invest
                        room.winOuts=outs
                        room.winOdds=calodds(outs)
                        for (let i = 0 ;i <room.playersMsg.length ; i++){
                            if (room.playersMsg[i].name === results.filter((a) => a.stair == 0)[0].player ){
                                room.playersMsg[i].isWinner = true
                                room.playersMsg[i].secondBuying = true //防止重复提交
                            }
                        }
                        //停止计时条
                        io.to(groupid).emit('coolDown', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
                        ));
                        io.to(groupid).emit('callInsurance',dataIns);
                        //返回信息
                        io.to(groupid).emit('rendering__game__to__client', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
                        ));
                        return
                    }else {
                        //非独赢
                        room.communityCardPoker.push(room.deck.pop())
                        room.currTurn = 3
                    }
                }
                if (room.currTurn == 3) {
                    console.log('牌发完了，比大小(allin)')
                    let results = revealCards(room.playersMsg, room.roundData.bets, room.roundData.preFlop, room.roundData.Flop, room.roundData.Turn, room.communityCardPoker, room.pot)
                    console.log(results)
                    //结算
                    for (players of room.playersMsg) {
                        if (results.findIndex((p) => p.player === players.name) != -1) {
                            players.statusChipsLeftover += results[results.findIndex((p) => p.player === players.name)].winpot
                            winpotdata = {
                                name: players.name,
                                hand: results[results.findIndex((p) => p.player === players.name)].handTitle,
                                pot: results[results.findIndex((p) => p.player === players.name)].winpot,
                            }
                            console.log(winpotdata)
                            room.winInfo.push({
                                name: players.name,
                                hand: results[results.findIndex((p) => p.player === players.name)].handTitle,
                                pot: results[results.findIndex((p) => p.player === players.name)].winpot,
                            })
                            io.to(groupid).emit('win',
                                {name: players.name,
                                    hand : results[results.findIndex((p) => p.player === players.name)].handTitle,
                                    pot: results[results.findIndex((p) => p.player === players.name)].winpot,
                                });
                        }
                    }
                    console.log(room.winInfo)
                    room.finish = true
                }
            }
        } else if (numNonFolds > 1) {//回合结束，两家含以上没弃牌，并且没有全部allin
            if (allPlayersPresent && allPlayersCall && room.isBBwent) {
                if (room.currTurn == 0) {
                    //初始化自动弃牌和过牌
                    for (let i = 0 ; i<room.playersMsg.length;i++){
                        room.playersMsg[i].autoFold = false;
                        room.playersMsg[i].autoCheck = false;
                    }
                    //清空下注显示
                    //返回信息
                    for (let i = 0 ;i <room.playersMsg.length;i++){
                        room.playersMsg[i].style='' ;
                        room.playersMsg[i].number=0;
                    }
                    io.to(groupid).emit('rendering__game__to__client', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
                    ));
                    //发翻牌
                    console.log('发翻牌')
                    room.communityCardPoker = [room.deck.pop(), room.deck.pop(), room.deck.pop()]
                    room.roundData.preFlop = room.roundData.bets
                    let count = 0;
                    let firstToGo = room.sbId-1 < 0? room.playersMsg.length-1 : room.sbId-1;
                    do {
                            firstToGo = firstToGo + 1 >= room.playersMsg.length ? 0 :  firstToGo + 1;
                            count++;
                    } while (
                            //弃牌或allin的跳过 机器人跳过
                            (room.playersMsg[firstToGo].isFold == true
                                || room.playersMsg[firstToGo].allIn == true
                            || room.playersMsg[firstToGo].robot == true)
                            && count < Object.keys(room.playersMsg).length * 2 // Avoid infinite loop, allow search twice on all players
                        );
                    room.playersMsg[firstToGo].isTrun = true;
                    room.roundData.bets = []
                    room.currTurn = 1
                    // timer = setTimeout(() => socket.emit('cooldownfold',
                    //     room.playersMsg[room.sbId].id), 10000)
                    // timer1 = setTimeout(() => socket.broadcast.emit('cooldownfold',
                    //     room.playersMsg[room.sbId.id), 10000)
                    io.to(groupid).emit('coolDown', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
                    ));
                    room.nowAnte = 0;
                } else if (room.currTurn == 1) {
                    //初始化自动弃牌和过牌
                    for (let i = 0 ; i<room.playersMsg.length;i++){
                        room.playersMsg[i].autoFold = false;
                        room.playersMsg[i].autoCheck = false;
                    }
                    //清空下注显示
                    //返回信息
                    for (let i = 0 ;i <room.playersMsg.length;i++){
                        room.playersMsg[i].style='' ;
                        room.playersMsg[i].number=0;
                    }
                    io.to(groupid).emit('rendering__game__to__client', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
                    ));
                    //发转牌
                    console.log('发转牌')
                    room.communityCardPoker.push(room.deck.pop());
                        room.roundData.Flop = room.roundData.bets
                    let count = 0;
                    let firstToGo = room.sbId-1 < 0? room.playersMsg.length-1 : room.sbId-1;
                    do {
                        firstToGo = firstToGo + 1 >= room.playersMsg.length ? 0 :  firstToGo + 1;
                        count++;
                    } while (
                        //弃牌或allin的跳过 机器人跳过
                    (room.playersMsg[firstToGo].isFold == true
                        || room.playersMsg[firstToGo].allIn == true
                        || room.playersMsg[firstToGo].robot == true)
                    && count < Object.keys(room.playersMsg).length * 2 // Avoid infinite loop, allow search twice on all players
                        );
                    room.playersMsg[firstToGo].isTrun = true;
                    room.roundData.bets = []
                    room.currTurn = 2
                    // timer = setTimeout(() => socket.emit('cooldownfold',
                    //     room.playersMsg[room.sbId].id), 10000)
                    // timer1 = setTimeout(() => socket.broadcast.emit('cooldownfold',
                    //     room.playersMsg[room.sbId].id), 10000)
                    io.to(groupid).emit('coolDown', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
                    ));
                    room.nowAnte = 0;
                }
                else if (room.currTurn == 2) {
                    //初始化自动弃牌和过牌
                    for (let i = 0 ; i<room.playersMsg.length;i++){
                        room.playersMsg[i].autoFold = false;
                        room.playersMsg[i].autoCheck = false;
                    }
                    //清空下注显示
                    //返回信息
                    for (let i = 0 ;i <room.playersMsg.length;i++){
                        room.playersMsg[i].style='' ;
                        room.playersMsg[i].number=0;
                    }
                    io.to(groupid).emit('rendering__game__to__client', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
                    ));
                    //发河底
                    console.log('河底')
                    room.communityCardPoker.push(room.deck.pop());
                        room.roundData.Turn = room.roundData.bets
                    let count = 0;
                    let firstToGo = room.sbId-1 < 0? room.playersMsg.length-1 : room.sbId-1;
                    do {
                        firstToGo = firstToGo + 1 >= room.playersMsg.length ? 0 :  firstToGo + 1;
                        count++;
                    } while (
                        //弃牌或allin的跳过 机器人跳过
                    (room.playersMsg[firstToGo].isFold == true
                        || room.playersMsg[firstToGo].allIn == true
                        || room.playersMsg[firstToGo].robot == true)
                    && count < Object.keys(room.playersMsg).length * 2 // Avoid infinite loop, allow search twice on all players
                        );
                    room.playersMsg[firstToGo].isTrun = true;
                    room.roundData.bets = []
                    room.currTurn = 3
                    // timer = setTimeout(() => socket.emit('cooldownfold',
                    //     room.playersMsg[room.sbId].id), 10000)
                    // timer1 = setTimeout(() => socket.broadcast.emit('cooldownfold',
                    //     room.playersMsg[room.sbId].id), 10000)
                    io.to(groupid).emit('coolDown', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
                    ));
                    room.nowAnte = 0;
                }
                else if (room.currTurn == 3) {
                    //摊牌
                    console.log('牌发完了，比大小(没有allin)')
                    for (let i=0;i <room.playersMsg.length ; i ++){
                        if (room.playersMsg[i].isFold != true){
                            room.playersMsg[i].showFlop = room.playersMsg[i].theFlop
                            console.log(room.playersMsg[i].showFlop)
                        }
                    }
                    let results = revealCards(room.playersMsg, room.roundData.bets, room.roundData.preFlop, room.roundData.Flop, room.roundData.Turn, room.communityCardPoker, room.pot)
                    //结算


                    for (players of room.playersMsg) {
                        if (results.findIndex((p) => p.player === players.name) != -1) {
                            players.statusChipsLeftover += results[results.findIndex((p) => p.player === players.name)].winpot
                            winpotdata = {
                                name: players.name,
                                hand: results[results.findIndex((p) => p.player === players.name)].handTitle,
                                pot: results[results.findIndex((p) => p.player === players.name)].winpot,
                            }
                            console.log(winpotdata)
                            room.winInfo.push({
                                name: players.name,
                                hand: results[results.findIndex((p) => p.player === players.name)].handTitle,
                                pot: results[results.findIndex((p) => p.player === players.name)].winpot,
                            });
                            io.to(groupid).emit('win',
                                {name: players.name,
                                hand : results[results.findIndex((p) => p.player === players.name)].handTitle,
                                pot: results[results.findIndex((p) => p.player === players.name)].winpot,
                                });
                        }
                    }
                    console.log(room.winInfo)
                    room.finish = true
                }
            } else {
                //回合没结束，下一位动作
                if (data.preFold != 1) {//不是提前弃牌或过牌
                    let count = 0;
                    do {
                        playersMsgIndex = playersMsgIndex + 1 >= room.playersMsg.length ? 0 : playersMsgIndex + 1;
                        count++;
                    } while (
                        //弃牌或allin的跳过 机器人跳过 提前弃牌过过牌的跳过
                        (room.playersMsg[playersMsgIndex].isFold == true
                            || room.playersMsg[playersMsgIndex].allIn == true
                        ||room.playersMsg[playersMsgIndex].robot==true)
                        && count < Object.keys(room.playersMsg).length * 2 // Avoid infinite loop, allow search twice on all players
                    );
                    room.playersMsg[playersMsgIndex].isTrun = true;
                    if (room.playersMsg[playersMsgIndex].autoCheck== true){
                        io.to(groupid).emit('autoCheck', room.playersMsg[playersMsgIndex].id);
                    }else if (room.playersMsg[playersMsgIndex].autoFold == true ){
                        io.to(groupid).emit('autoFold', room.playersMsg[playersMsgIndex].id);
                    }

                }
                //开启弃牌计时
                // timer = setTimeout(() => socket.emit('cooldownfold',
                //     room.playersMsg[playersMsgIndex].id), 10000)
                // timer1 = setTimeout(() => socket.broadcast.emit('cooldownfold',
                //     room.playersMsg[playersMsgIndex].id), 10000)
                io.to(groupid).emit('coolDown', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
                ));

            }
        }



        //返回信息
        io.to(groupid).emit('rendering__game__to__client', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
        ));

        if (room.finish == true) {
            room.isStart = false
            console.log('game finish')
            console.log('isstart?'+room.isStart)
            //清空下注显示
            //这里返回 isStart
            io.to(groupid).emit('rendering__game__to__client', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
            ));
            setTimeout(() => socket.emit('start__game__to__client',
                {}), 5000)
        }


        //
        // }

        // 打印日志
        // fs.appendFile(
        //     './log.txt',
        //     `id为:${data.id}的用户，执行了${data.style}的操作。`,
        //     err => {
        //         if (err) { console.error(err); }
        //     });
    });

    //买入
    socket.on('buyIn', function (data) {
        var room = rooms.find((array => array.roomNumber === data.roomNumber));
        var playersMsgIndex = room.playersMsg.findIndex((array => array.id === data.id));
        room.playersMsg[playersMsgIndex].buyIns += data.number
    });
    //亮牌
    socket.on('showCard', function (data) {
        var room = rooms.find((array => array.roomNumber === data.roomNumber));
        var playersMsgIndex = room.playersMsg.findIndex((array => array.id === data.id));
        if ( room.playersMsg[playersMsgIndex].showFlop.length ==0) {
            room.playersMsg[playersMsgIndex].showFlop.push(room.playersMsg[playersMsgIndex].theFlop[data.card])
            io.to(groupid).emit('rendering__game__to__client', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
            ));
            setTimeout(() => {
                    room.playersMsg[playersMsgIndex].showFlop = [];
                    io.to(groupid).emit('rendering__game__to__client', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
                    ))
                },
                2000)
        }
    });

    socket.on('leave', function (data) {
        var room = rooms.find((array => array.roomNumber === data.roomNumber));
        var playersMsgIndex = room.playersMsg.findIndex((array => array.id === data.id));
        room.playersMsg[playersMsgIndex].exit = true
        io.to(groupid).emit('rendering__game__to__client', JSON.stringify(rooms.find((array => array.roomNumber === data.roomNumber))
        ));
        //托管
    });
    socket.on('back', function (data) {
        var room = rooms.find((array => array.roomNumber === data.roomNumber));
        var playersMsgIndex = room.playersMsg.findIndex((array => array.id === data.id));
        room.playersMsg[playersMsgIndex].exit = false
        //取消托管
    });


})

// y用户数据
global.MysqlPlayersMsg = [
    {
        id: '0000006',
        name: '空位1',
        avatar: './images/avatar/loppy.png',
        statusChipsLeftover: 0,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 0,
        exit: true,
        style: '',
        number: '',
        robot:true,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },{
        id: '9999999',
        name: '空位2',
        avatar: './images/avatar/loppy.png',
        statusChipsLeftover: 0,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 0,
        exit: true,
        style: '',
        number: '',
        robot:true,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },{
        id: '9999998',
        name: '空位3',
        avatar: './images/avatar/loppy.png',
        statusChipsLeftover: 0,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 0,
        exit: true,
        style: '',
        number: '',
        robot:true,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },{
        id: '9999997',
        name: '空位4',
        avatar: './images/avatar/loppy.png',
        statusChipsLeftover: 0,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 0,
        exit: true,
        style: '',
        number: '',
        robot:true,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },{
        id: '9999996',
        name: '空位5',
        avatar: './images/avatar/loppy.png',
        statusChipsLeftover: 0,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 0,
        exit: true,
        style: '',
        number: '',
        robot:true,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },{
        id: '9999995',
        name: '空位6',
        avatar: './images/avatar/loppy.png',
        statusChipsLeftover: 0,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 0,
        exit: true,
        style: '',
        number: '',
        robot:true,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },{
        id: '9999994',
        name: '空位7',
        avatar: './images/avatar/loppy.png',
        statusChipsLeftover: 0,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 0,
        exit: true,
        style: '',
        number: '',
        robot:true,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },{
        id: '9999993',
        name: '空位8',
        avatar: './images/avatar/loppy.png',
        statusChipsLeftover: 0,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 0,
        exit: true,
        style: '',
        number: '',
        robot:true,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },{
        id: '9999992',
        name: '空位0',
        avatar: './images/avatar/loppy.png',
        statusChipsLeftover: 0,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 0,
        exit: true,
        style: '',
        number: '',
        robot:true,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },
    {
        id: '0021',
        name: '涛哥',
        avatar: './images/avatar/text_1.jpg',
        statusChipsLeftover: 2000,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 2000,
        exit: false,
        style: '',
        number: '',
        robot:false,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },
    {
        id: '0132',
        name: 'old',
        avatar: './images/avatar/old.png',
        statusChipsLeftover: 2000,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 2000,
        exit: false,
        style: '',
        number: '',
        robot:false,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },
    {
        id: '0103',
        name: '二哥',
        avatar: './images/avatar/erge.png',
        statusChipsLeftover: 2000,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 2000,
        exit: false,
        style: '',
        number: '',
        robot:false,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },
    {
        id: '7004',
        name: '佳佳',
        avatar: './images/avatar/jiasang.png',
        statusChipsLeftover: 2000,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 2000,
        exit: false,
        style: '',
        number: '',
        robot:false,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },
    {
        id: '0000005',
        name: '天蝎座',
        avatar: './images/avatar/text_5.jpg',
        statusChipsLeftover: 2000,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 2000,
        exit: false,
        style: '',
        number: '',
        robot:false,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },
    {
        id: '0000007',
        name: '澳大利',
        avatar: './images/avatar/text_7.jpg',
        statusChipsLeftover: 2000,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 2000,
        exit: false,
        style: '',
        number: '',
        robot:false,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },
    {
        id: '0000008',
        name: 'uusee',
        avatar: './images/avatar/text_8.jpg',
        statusChipsLeftover: 5656,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 1000,
        exit: false,
        style: '',
        number: '',
        robot:false,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    },
    {
        id: '644644',
        name: '管理员',
        avatar: './images/avatar/9.png',
        statusChipsLeftover: 0,
        theFlop: [],
        buyIns: 0,
        blindValue: '',
        isDealer: false,
        allIn: false,
        isTrun: false,
        isFold: true,
        bringIn: 1000,
        exit: false,
        style: '',
        number: '',
        robot:false,
        showFlop:[],
        isWinner:false,
        buying:false,
        secondBuying :false,
        isDown :false,
        autoFold:false,
        autoCheck:false,
    }
]

// 扑克牌
function shuffle(arr) {
    if (!arr) {
        throw '错误，请传入正确数组';
    }

    var newArr = arr.slice(0);
    for (var i = newArr.length - 1; i >= 0; i--) {
        var randomIndex = Math.floor(Math.random() * (i + 1));
        var itemAtIndex = newArr[randomIndex];
        newArr[randomIndex] = newArr[i];
        newArr[i] = itemAtIndex;
    }

    return newArr;
}


function generatePoker() {
    var cardType = ["s", "h", "c", "d"];

    var cardValue = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'];

    var allCards = [];
    for (var i = 0,
        len1 = cardType.length; i < len1; i++) {
        for (var j = 0,
            len2 = cardValue.length; j < len2; j++) {
            allCards.push(cardValue[j] + cardType[i]);
        }
    }

    return allCards;
}


function dealPoker() {
    // if (!num || num > 52 || typeof (num) !== 'number') {
    //     throw '错误，传入的数字非法，只能是[1-54]';
    // }

    var allCards = generatePoker();

    var deck = shuffle(allCards);
    return deck

}
function arraysEqual(a, b) {
    if (a === b) return true;
    if (a == null || b == null) return false;
    if (a.length != b.length) return false;

    for (let i = 0; i < a.length; ++i) {
        if (a[i] != b[i]) return false;
    }
    return true;
};
function totalInvest (playersMsg, curbet, preFlop, Flop, Turn){
    let currtotalInvest = [];
    for (i = 0; i < playersMsg.length; i++) {
        if (playersMsg[i].isFold == false) {//没弃牌的 河底发完牌统一计算投入
            let pfp = preFlop.find((item) => item.player === playersMsg[i].id) == undefined ? 0 :
                preFlop.find((item) => item.player === playersMsg[i].id).bet;
            let fp = Flop.find((item) => item.player === playersMsg[i].id) == undefined ? 0 :
                Flop.find((item) => item.player === playersMsg[i].id).bet;
            let tn = Turn.find((item) => item.player === playersMsg[i].id) == undefined ? 0 :
                Turn.find((item) => item.player === playersMsg[i].id).bet;
            let thisround = curbet.find((item) => item.player === playersMsg[i].id) == undefined ? 0 :
                curbet.find((item) => item.player === playersMsg[i].id).bet;
            currtotalInvest.push(
                {
                    player: playersMsg[i].name,
                    bet: pfp + fp + tn + thisround,
                },
            )
            currtotalInvest = currtotalInvest.sort((a, b) =>
                a.bet > b.bet ? -1 : 1
            );
        }
    }
    return currtotalInvest
}
function revealCards(playersMsg, curbet, preFlop, Flop, Turn, communityCardPoker, pot) {//比大小有点问题，两对没有一对大或者没计算转盘和河底 把所有牌型打印出来看一下
    let currtotalInvest = [];
    for (i = 0; i < playersMsg.length; i++) {
        if (playersMsg[i].isFold == false) {//没弃牌的 河底发完牌统一计算投入
            let pfp = preFlop.find((item) => item.player === playersMsg[i].id) == undefined ? 0 :
                preFlop.find((item) => item.player === playersMsg[i].id).bet;
            let fp = Flop.find((item) => item.player === playersMsg[i].id) == undefined ? 0 :
                Flop.find((item) => item.player === playersMsg[i].id).bet;
            let tn = Turn.find((item) => item.player === playersMsg[i].id) == undefined ? 0 :
                Turn.find((item) => item.player === playersMsg[i].id).bet;
            let thisround = curbet.find((item) => item.player === playersMsg[i].id) == undefined ? 0 :
                curbet.find((item) => item.player === playersMsg[i].id).bet;
            currtotalInvest.push(
                {
                    player: playersMsg[i].name,
                    bet: pfp + fp + tn + thisround,
                },
            )
            currtotalInvest = currtotalInvest.sort((a, b) =>
                a.bet > b.bet ? -1 : 1
            );
        }
    }
    let winners;
    let results = [];
    let stair = 0

    do {
        let handArray = [];
        let playerArray = [];
        for (let i = 0; i < playersMsg.length; i++) {
            if (playersMsg[i].isFold == false) {
                let h = Hand.solve(playersMsg[i].theFlop.concat(communityCardPoker));
                handArray.push(h);
                playerArray.push({ player: playersMsg[i].name, hand: h });
            }
        }
        winners = Hand.winners(handArray);
        let winnerData = [];
        if (Array.isArray(winners)) {
            for (playerHand of playerArray) {
                for (winner of winners) {
                    let winnerArray = winner.toString().split(', ');
                    if (
                        arraysEqual(playerHand.hand.cards.sort(), winnerArray.sort())
                    ) {
                        winnerData.push({
                            player: playerHand.player,
                            rank: playerHand.hand.rank,
                            handTitle: playerHand.hand.name,
                            winpot: 0,
                            stair: stair,
                            invest: currtotalInvest.find((item) => item.player === playerHand.player).bet,
                        });
                        break;
                    }
                }
            }
        }
        for (winner of winnerData) {
            let nonConcernpot = 0
            for (i = 0; i <= currtotalInvest.findIndex((item) => item.player === winner.player); i++) {
                nonConcernpot = nonConcernpot + currtotalInvest[i].bet
                    - currtotalInvest.find((item) => item.player === winner.player).bet
            }
            winner.winpot = pot - nonConcernpot
            playersMsg = playersMsg.filter((a) => a.name != winner.player)
        }
        //计算分池的钱
        winnerData = winnerData.sort((a, b) => a.winpot > b.winpot ? -1 : 1)
        winnerData[winnerData.length - 1].winpot = (winnerData[winnerData.length - 1].winpot) / winnerData.length
        let potThisround = winnerData[winnerData.length - 1].winpot;
        for (i = winnerData.length - 1; i > 0; i--) {
            winnerData[i - 1].winpot = (winnerData[i - 1].winpot - (i + 1) * winnerData[i].winpot) / i + winnerData[i].winpot
            potThisround += winnerData[i - 1].winpot
        }
        pot = pot - potThisround
        for (i = 0; i < winnerData.length; i++) {
            results.push(winnerData[i])
        }
        stair++
    }
    while (pot > 0)//边池赢家
    return results  //(name handrank handname winpot stair invest)
}

function calodds(outs) {
    let odds; //对应不同反超牌数量计算赔率
    if (outs.length == 0) {
        odds = 100
    }
    else if (outs.length == 1) {
        odds = 29
    }
    else if (outs.length == 2) {
        odds = 15
    }
    else if (outs.length == 3) {
        odds = 10
    }
    else if (outs.length == 4) {
        odds = 7
    }
    else if (outs.length == 5) {
        odds = 6
    }
    else if (outs.length == 6) {
        odds = 4.5
    }
    else if (outs.length == 7) {
        odds = 3.5
    }
    else if (outs.length == 8) {
        odds = 3
    }
    else if (outs.length == 9) {
        odds = 2.8
    }
    else if (outs.length == 10) {
        odds = 2.5
    }
    else if (outs.length == 11) {
        odds = 2.3
    }
    else if (outs.length == 12) {
        odds = 2
    }
    else if (outs.length == 13) {
        odds = 1.8
    }
    else if (outs.length == 14) {
        odds = 1.5
    }
    else {
        odds = 1
    }
    return odds
}



